package com.example.manualManagement.service.impl.user.account;

import com.example.manualManagement.entity.Manage;
import com.example.manualManagement.service.impl.UserDetailsImpl;
import com.example.manualManagement.service.user.account.LoginService;
import com.example.manualManagement.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public Map<String, String> getToken(String userName, String userPassword) {

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userName, userPassword);

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
        Manage manage = loginUser.getManage();
        String jwt = JwtUtil.createJWT(manage.getUserid().toString());

        Map<String, String> map = new HashMap<>();
        map.put("error_massage", "success");
        map.put("token", jwt);

        return map;

    }
}
